import 'package:awak/common/values/svg.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:awak/bloc/auth/auth_bloc.dart';
import 'package:awak/bloc/auth/auth_event.dart';
import 'package:awak/bloc/auth/auth_state.dart';
import 'package:awak/common/models/chat.dart';
import 'package:awak/common/models/user.dart';


class ChatProfilePage extends StatefulWidget {
  final User otherUser;

  const ChatProfilePage({Key? key, required this.otherUser}) : super(key: key);

  @override
  State<ChatProfilePage> createState() => _ChatProfilePageState();
}

class _ChatProfilePageState extends State<ChatProfilePage> {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _loadChatMessages();
  }

  void _loadChatMessages() {
    final currentUser = context.read<AwakBloc>().userRepository.currentUser;
    if (currentUser != null) {
      // 标记消息为已读
      context.read<AwakBloc>().add(
        MarkMessagesAsReadEvent(currentUser.id!, widget.otherUser.id!)
      );

      // 加载聊天消息
      context.read<AwakBloc>().add(
        FetchChatMessagesEvent(currentUser.id!, widget.otherUser.id!)
      );
    }
  }

  void _sendMessage() {
    final content = _messageController.text.trim();
    if (content.isEmpty) return;

    final currentUser = context.read<AwakBloc>().userRepository.currentUser;
    if (currentUser == null) return;

    final chat = Chat(
      sendUserId: currentUser.id!,
      acceptUserId: widget.otherUser.id!,
      context: content,
      sendTime: DateTime.now(),
    );

    context.read<AwakBloc>().add(SendChatMessageEvent(chat));
    _messageController.clear();

    // 滚动到底部
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.center,
            colors: [Color(0xFFD3F524), Colors.white],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 标题栏
              Container(
                height: 60.h,
                padding: EdgeInsets.symmetric(horizontal: 16.w),
                child: Row(
                  children: [
                    // 返回按钮
                    GestureDetector(
                      onTap: () => Beamer.of(context).beamBack(),
                      child: Icon(
                        AwakSvg.back,
                        size: 20.w,
                        color: Colors.black,
                      ),
                    ),
                    Expanded(
                      child: Center(
                        child: Text(
                          'Chat',
                          style: TextStyle(
                            fontSize: 24.sp,
                            fontWeight: FontWeight.bold,
                            color: Colors.black,
                          ),
                        ),
                      ),
                    ),
                    // 举报按钮
                    GestureDetector(
                      onTap: () {
                      },
                      child: Icon(
                        AwakSvg.report,
                        size: 24.sp,
                        color: Colors.black,
                      ),
                    ),
                  ],
                ),
              ),

              // 聊天内容区域
              Expanded(
                child: BlocBuilder<AwakBloc, AwakState>(
                  builder: (context, state) {
                    if (state is ChatLoading) {
                      return const Center(child: CircularProgressIndicator());
                    }

                    if (state is ChatMessagesLoaded) {
                      return _buildChatList(state.messages, state.currentUser);
                    }

                    if (state is ChatFailure) {
                      return Center(
                        child: Text(
                          state.message,
                          style: TextStyle(color: Colors.red, fontSize: 16.sp),
                        ),
                      );
                    }

                    return const Center(child: Text('No messages yet'));
                  },
                ),
              ),

              // 底部发送框
              Container(
                padding: EdgeInsets.all(16.w),
                child: Row(
                  children: [
                    Expanded(
                      child: Container(
                        height: 44.h,
                        decoration: BoxDecoration(
                          color: const Color(0xFFFEF463),
                          borderRadius: BorderRadius.circular(12.r),
                          border: Border.all(color: Colors.black, width: 2.w),
                        ),
                        alignment: Alignment.centerLeft,
                        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 2.h),
                        child: TextField(
                          controller: _messageController,
                          decoration: InputDecoration(
                            hintText: 'Send A Message',
                            hintStyle: TextStyle(
                              color: const Color(0xFFCDCDCD),
                              fontWeight: FontWeight.w600,
                              fontSize: 16.sp,
                            ),
                            border: InputBorder.none,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 8.w),
                    GestureDetector(
                      onTap: _sendMessage,
                      child: Container(
                        height: 44.h,
                        padding: EdgeInsets.symmetric(horizontal: 18.w),
                        decoration: BoxDecoration(
                          color: Colors.black,
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                        child: Center(
                          child: Text(
                            'Send',
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 16.sp,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildChatList(List<Chat> messages, User? currentUser) {
    if (messages.isEmpty) {
      return Center(
        child: Text(
          'No messages yet',
          style: TextStyle(
            color: Colors.grey,
            fontSize: 16.sp,
          ),
        ),
      );
    }

    return ListView.builder(
      controller: _scrollController,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      itemCount: messages.length,
      itemBuilder: (context, index) {
        final message = messages[index];
        final isMe = message.sendUserId == currentUser?.id;

        return _buildMessageBubble(message, isMe);
      },
    );
  }

  Widget _buildMessageBubble(Chat message, bool isMe) {
    final currentUser = context.read<AwakBloc>().userRepository.currentUser;

    return Container(
      margin: EdgeInsets.symmetric(vertical: 8.h),
      child: Row(
        mainAxisAlignment: isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isMe) ...[
            // 对方头像
            CircleAvatar(
              radius: 24.r,
              backgroundImage: AssetImage(widget.otherUser.avatar ?? ''),
            ),
            SizedBox(width: 12.w),
          ],

          // 消息气泡
          Flexible(
            child: Column(
              crossAxisAlignment: isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
              children: [
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
                  decoration: BoxDecoration(
                    color: isMe ? const Color(0xFFD3F524) : const Color(0xFFF4F4F4),
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: Text(
                    message.context,
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 14.sp,
                    ),
                  ),
                ),
                SizedBox(height: 2.h),
                Text(
                  '${message.sendTime.hour.toString().padLeft(2, '0')}:${message.sendTime.minute.toString().padLeft(2, '0')}',
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 12.sp,
                  ),
                ),
              ],
            ),
          ),

          if (isMe) ...[
            SizedBox(width: 12.w),
            // 自己的头像
            CircleAvatar(
              radius: 24.r,
              backgroundImage: AssetImage(currentUser?.avatar ?? ''),
            ),
          ],
        ],
      ),
    );
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    super.dispose();
  }
}